package com.ymatou.query.trading.api.parameter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;

import com.ymatou.query.seller.trading.api.parameter.Common;
import com.ymatou.query.seller.trading.api.parameter.OrderEntities;
import com.ymatou.query.seller.trading.api.parameter.Ymt_BillExtension;
import com.ymatou.query.seller.trading.api.parameter.Ymt_O_OrderNote;
import com.ymatou.query.seller.trading.api.parameter.Ymt_Order;
import com.ymatou.query.seller.trading.api.parameter.Ymt_OrderExtension;
import com.ymatou.query.seller.trading.api.parameter.Ymt_OrderInfo;
import com.ymatou.query.seller.trading.api.parameter.Ymt_OrderInfoExtension;
import com.ymatou.query.seller.trading.api.parameter.Ymt_OrderState;
import com.ymatou.query.seller.trading.api.parameter.Ymt_OrderSummary;
import com.ymatou.query.seller.trading.api.parameter.Ymt_OrderSummaryExtension;
import com.ymttest.common.entitie.BillInfo;
import com.ymttest.common.entitie.C2COrderInfo;
import com.ymttest.common.entitie.C2COrderInfo.C2COrderInfoExt;
import com.ymttest.common.entitie.C2COrderInfo.OrderProductInfos;
import com.ymttest.common.entitie.C2COrderInfo.RefundBillInfo;
import com.ymttest.common.entitie.OrderItemInfo;
import com.ymttest.common.entitie.ProductInfo.ProductInfoExt;
import com.ymttest.common.enums.LogisticsTypeEnum;
import com.ymttest.common.enums.OrderStatusEnum;
import com.ymttest.common.enums.OrderTypeEnum;
import com.ymttest.common.enums.PlatformEnum;
import com.ymttest.common.enums.SalesTypeStringEnum;
import com.ymttest.common.enums.StockStatusEnum;
import com.ymttest.database.model.Ymt_Bill;
import com.ymttest.database.model.Ymt_CreditDetail;
import com.ymttest.database.model.Ymt_OrderExt;
import com.ymttest.database.model.Ymt_OrderPostPay;
import com.ymttest.database.model.Ymt_OrderToBill;
import com.ymttest.database.model.Ymt_Order_Frozen;
import com.ymttest.database.model.Ymt_TradingItem;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.DataUtil.KeyValuePair;
import com.ymttest.utils.YMTDateUtil;

public class OrderConverter {
	private static String defaultDateTime = "0001-01-01 00:00:00";

	public static com.ymttest.database.model.ProductPromotion GetPromotion(
					com.ymatou.query.seller.trading.api.parameter.Ymt_OrderInfo info) {
		if (info == null || DataUtil.Integerr.GetValueOrDefault(info.getPromotionId()) == 0) {
			return null;
		}
		com.ymttest.database.model.ProductPromotion pp = new com.ymttest.database.model.ProductPromotion();
		pp.setID(DataUtil.Integerr.GetValueOrDefault(info.getPromotionId()));
		pp.setCondition(info.getMatchCondition());
		pp.setContent(info.getPromotionValue());
		pp.setName(info.getPromotionName());
		pp.setReducedAmount(DataUtil.BigDecimall.GetValueOrDefault(info.getReducedAmount()));
		pp.setType(DataUtil.Integerr.GetValueOrDefault(info.getPromotionType()));
		pp.setPartialReducedAmount(DataUtil.BigDecimall.GetValueOrDefault(info.getfSellerPromotionAmount()));
		return pp;
	}

	public static List<OrderInfo> AsOrderInfos(OrderProductInfos orders, boolean detail) {
		return BuyerAppOrderInfoBuilder.Instance.GetOrderInfos(orders, detail);
	}

	public static class BuyerAppOrderInfoBuilder {
		public static BuyerAppOrderInfoBuilder Instance = new BuyerAppOrderInfoBuilder();

		public List<OrderInfo> GetOrderInfos(OrderProductInfos orders, boolean detail) {
			if (orders == null) {
				return null;
			}
			List<OrderInfo> result = new ArrayList<OrderInfo>();
			List<ProductInfoExt> products = orders.getProductInfos();
			List<RefundBillInfo> refunds = orders.getRefundBillInfos();
			for (C2COrderInfoExt order : orders.getOrderInfos()) {
				RefundBillInfo refund = null;
				List<RefundBillInfo> orderInRefunds = refunds.stream()
								.filter(a -> a.getOrderId() == order.getiOrderId()).collect(Collectors.toList());
				if (!DataUtil.isNullOrEmpty(orderInRefunds)) {
					refund = orderInRefunds.get(0);
				}
				result.add(GetOrderInfo(order, products.stream().filter(a -> a.getiOrderId() == order.getiOrderId())
								.collect(Collectors.toList()), refund, detail));
			}
			return result;
		}

		public OrderInfo GetOrderInfo(C2COrderInfoExt order, List<ProductInfoExt> products, RefundBillInfo refund,
						boolean detail) {
			OrderInfo info = new OrderInfo();
			info.setOrderGroupId(order.getiMainOrderId());
			info.setOrderId(order.getiOrderId());
			info.setAddTime(order.getdAddTime());
			int platform = DataUtil.Stringg.IsNullOrWhiteSpace(order.getsOrderSource()) ? PlatformEnum.Unknown
							.getValue() : GetPlatformEnumInfo(order.getiOrderType(), order.getsOrderSource());
			info.setPlatform(platform);
			info.setShangou(order.isbShangouOrder());
			info.setCancelReason(order.getsReason());
			info.setEvaluated(order.isbEvaluated());

			StatusInfo status = new StatusInfo();
			status.setOrderStatus(order.getiTradingStatus());
			status.setThirdPartyRefundStatus(order.getiThirdPartyRefundStatus());
			status.setSalesRefundStatus(order.getiSalesRefundStatus());
			info.setStatus(status);

			SellerInfo seller = new SellerInfo();
			seller.setUserId(order.getiBuyerId());
			seller.setSellerNote(order.getSellerNote());
			seller.setSellerLoginId(order.getsSellerLoginId());
			info.setSeller(seller);

			ConsigneeInfo consignee = new ConsigneeInfo();
			consignee.setName(order.getsReceivePerson());
			consignee.setPhone(order.getsPhone());
			consignee.setTel(order.getsTelephone());
			consignee.setAddress(order.getsAddress());
			consignee.setPostcode(order.getsPostCode());
			info.setConsignee(consignee);

			ConsumerInfo consumer = new ConsumerInfo();
			consumer.setUserId(order.getiUserId());
			consumer.setNeedUploadIDCard(order.isbIsNeedUploadIdCard());
			boolean iDCardUpdated = order.isbHaveUploadedIdCard()
							|| !DataUtil.Stringg.isNullOrEmpty(order.getIdCardUploadedKey());
			consumer.setIDCardUpdated(iDCardUpdated);
			consumer.setLeaveWord(order.getsLeaveWord());
			info.setConsumer(consumer);
			info.setPayment(GetPaymentInfo(order, refund, detail));
			info.setTransfer(GetTransferInfo(order));
			info.setProducts(GetProductInfos(products));
			info.setAutoCancelOrderHours(order.getfAutoCancelOrderHours());

			OrderOperationArguments args = new OrderOperationArguments();
			args.setiOrderId(order.getiOrderId());
			args.setiTradingStatus(order.getiTradingStatus());
			args.setbShangouOrder(order.isbShangouOrder());
			args.setbPaidInFull(order.isbPaidInFull());
			args.setdPostPaidTime(order.getdPostPaidTime());
			args.setdAcceptTime(order.getdAcceptTime());
			args.setdPaidTime(order.getdPaidTime());
			args.setdDispathTime(order.getdDispathTime());
			args.setdConfirmedTime(order.getdConfirmedTime());

			OrderOperationInfo operation = args.Convert();
			info.setOperation(operation);

			return info;
		}

		public List<ProductInfo> GetProductInfos(List<ProductInfoExt> products) {
			List<ProductInfo> infos = new ArrayList<ProductInfo>();
			if (products == null) {
				return null;
			}
			for (ProductInfoExt product : products) {
				infos.add(GetProductInfo(product));
			}
			return infos;
		}

		public ProductInfo GetProductInfo(ProductInfoExt product) {
			ProductInfo info = new ProductInfo();
			if (product == null) {
				return null;
			}
			info.setBondedArea(DataUtil.Integerr.GetValueOrDefault(product.getiBondedArea()));
			info.setCatalogId(product.getsCatalogId());
			info.setCatalogInfo(product.getsPropertyInfo());
			boolean deliveryFromBonded = product.getiCatalogStatus() == LogisticsTypeEnum.BondedDelivery.getValue()
							|| product.getiCatalogStatus() == LogisticsTypeEnum.XloboBondedDelivery.getValue();
			info.setDeliveryFromBonded(deliveryFromBonded);
			info.setIsActivityProduct(product.getiActivityId() > 0);
			info.setLogisticsType(product.getiCatalogStatus());
			info.setPriceType(product.getiPriceType());
			info.setProductDescription(product.getsTitle());
			info.setProductId(product.getsProductId());
			info.setProductPicUrl(product.getsPictureUrl());
			info.setProductsNum(product.getiAmount());
			info.setProductSoldPrice(product.getfProductPrice());
			info.setTariffType(product.getiTariffType());
			info.setProductRefundChannel(product.getiProductRefundChannel());
			boolean productRefund = product.getiProductRefundStatus() != null && product.getiProductRefundStatus() != 0;
			info.setProductRefund(productRefund);
			info.setPackageNo(product.getsPackageNo());
			info.setProductInfoString(product.getsProductInfo());
			info.setSalesType(SalesTypeStringEnum.forValue(product.getiSalesType()).name());
			info.setSalesRefundStatus(product.getiProductRefundStatus());
			info.setProductOriginalPrice(DataUtil.BigDecimall.GetValueOrDefault(product.getfProductOriginalPrice()));
			info.setFreightFree(product.getbFreightFree());
			return info;
		}

		public PaymentInfo GetPaymentInfo(C2COrderInfo order, RefundBillInfo refund, boolean detail) {
			PaymentInfo info = new PaymentInfo();
			info.setOnlyNeedPayOnce(!order.isbShangouOrder());// 是否仅需付款一次
			info.setCouponValue(order.getCouponValue());
			info.setCouponCode(order.getsCouponCode());
			info.setSellerCouponAmount(order.getfSellerCouponAmount());
			info.setSellerCouponCode(order.getsSellerCouponCode());
			info.setEarnest(order.getfOrderPrice().add(order.getfOrderDiscount()));
			info.setFirstPay(GetPrePaidAmount(order));
			info.setNeedPostpayAmount(GetNeedPostpayAmount(order));
			info.setPostPaidAmountOfGift(order.getfPostPaidAmountOfGift());
			info.setRealPay(GetAmountOfRealPay(order));
			info.setRealPostPay(GetPostPaidAmount(order));
			info.setFreight(order.getfFreight());
			info.setGiftUsedAmountOfPostpay(order.getPostpayUseGiftAmount());
			// cation, setsetLastPayTime(...) may be a keng
			int fAutoCancelOrderHours = Integer.valueOf(DataUtil.BigDecimall.format("0",
							order.getfAutoCancelOrderHours()));
			info.setLastPayTime(YMTDateUtil.getBeforeOrNextHour(order.getdAddTime(), fAutoCancelOrderHours));
			info.setPaidInFull(order.isbPaidInFull());
			BigDecimal totalPrice = order.isbShangouOrder() ? order.getfTotalPrice() : order.getfOrderPrice();
			info.setTotalPrice(totalPrice);
			info.setTradingId(order.getiTradingId());
			info.setUseGiftAmount(order.getfUseGiftAmount());
			info.setTotalPriceChange(DataUtil.BigDecimall.GetValueOrDefault(order.getfOrderDiscount()));

			if (order.isbShangouOrder()) {
				info.setTotalEarnest(order.getfOrderPrice());
				BigDecimal tmp = order.getfTotalPrice().subtract(order.getfOrderPrice());
				BigDecimal originalPostpayAmount = tmp.compareTo(new BigDecimal(0)) > 0 ? tmp : new BigDecimal(0);
				info.setOriginalPostpayAmount(originalPostpayAmount);
				info.setActualPostpayAmount(order.getPostpayAmount());
				BigDecimal expectedPostpayAmount = order.isbPaidInFull() && order.getPostpayAmount() == null ? new BigDecimal(
								0) : DataUtil.BigDecimall.GetValueOrDefault(info.getActualPostpayAmount(),
								info.getOriginalPostpayAmount());
				info.setExpectedPostpayAmount(expectedPostpayAmount);
				info.setExpectedPayAmount(info.getTotalEarnest().add(info.getExpectedPostpayAmount()));
				if (info.getActualPostpayAmount() != null) {
					info.setPostpayPriceChange(info.getActualPostpayAmount().subtract(info.getOriginalPostpayAmount()));
				}
			} else {
				info.setExpectedPayAmount(order.getfOrderPrice());
			}
			if (refund != null) {
				info.setSalesRefundAmount(refund.getRefundAmount());
			}
			if (detail) {
				info.setDetail(GetPaymentDetail(info, order));
			}
			return info;
		}

		public PaymentDetail GetPaymentDetail(PaymentInfo info, C2COrderInfo order) {
			PaymentDetail detail = new PaymentDetail();
			if (info.getFirstPay().compareTo(new BigDecimal(0)) <= 0) {
				return null;
			}
			PaymentDetailItem earnest = new PaymentDetailItem();
			if (order.getfPaidAmountOfCash().compareTo(new BigDecimal(0)) > 0) {
				KeyValuePair<String, BigDecimal> o = GetPaidInfo(order.getThirdPartyPaidInfo());
				if (o != null) {
					earnest.setThirdPartyName(GetThirdPartyName(o.getKey()));
					earnest.setThirdParty(o.getValue());
					earnest.setAccount(order.getfPaidAmountOfCash().subtract(o.getValue()));
				} else {
					earnest.setAccount(order.getfPaidAmountOfCash());
				}
			}
			earnest.setGift(order.getfPaidAmountOfGift());
			earnest.setCoupon(order.getfPaidAmountOfCoupon());
			earnest.setFreeCard(order.getfPaidAmountOfFreeCard());
			detail.setEarnest(earnest);

			if (info.getRealPostPay().compareTo(new BigDecimal(0)) > 0) {
				PaymentDetailItem postpay = new PaymentDetailItem();
				if (order.getfPostPaidAmountOfCash().compareTo(new BigDecimal(0)) > 0) {
					KeyValuePair<String, BigDecimal> o = GetPaidInfo(order.getThirdPartyPostpaidInfo());
					if (o != null) {
						postpay.setThirdPartyName(GetThirdPartyName(o.getKey()));
						postpay.setThirdParty(o.getValue());
						postpay.setAccount(order.getfPostPaidAmountOfCash().subtract(o.getValue()));
					} else {
						postpay.setAccount(order.getfPostPaidAmountOfCash());
					}
					postpay.setGift(order.getfPostPaidAmountOfGift());
					postpay.setCoupon(order.getfPostPadiAmountOfCoupon());
				}
				detail.setPostpay(postpay);
			}
			return detail;
		}

		public String GetThirdPartyName(String s) {
			if (DataUtil.Stringg.isNullOrEmpty(s))
				return StringUtils.EMPTY;

			s = s.trim().toLowerCase();
			return s.equals("weixin") ? "wechat" : s;
		}

		public KeyValuePair<String, BigDecimal> GetPaidInfo(String s) {
			KeyValuePair<String, BigDecimal> paidInfo = new KeyValuePair<String, BigDecimal>();
			if (DataUtil.Stringg.isNullOrEmpty(s)) {
				return null;
			}
			String[] t = s.split("\\|");
			if (t.length != 2 || DataUtil.Stringg.isNullOrEmpty(t[0])) {
				return null;
			}
			BigDecimal x = new BigDecimal(t[0]);
			if (x == null || x.compareTo(new BigDecimal(0)) <= 0) {
				return null;
			}
			paidInfo.setKey(t[1]);
			paidInfo.setValue(x);
			return paidInfo;
		}

		public static BigDecimal GetNeedPostpayAmount(C2COrderInfo order) {
			return order.getiTradingStatus() == OrderStatusEnum.ApplyForPostPay.getValue() ? order.getPostpayAmount()
							: null;
		}

		public TransferInfo GetTransferInfo(C2COrderInfo order) {
			TransferInfo info = new TransferInfo();
			info.setAutoReceiveTime(GetAutoReceiveTime(order));
			boolean isDelayAutoReceiveTime = order.getiFrozenUserId() != null
							&& order.getiFrozenUserId() == order.getiUserId();
			info.setIsDelayAutoReceiveTime(isDelayAutoReceiveTime);
			info.setLocalRefundApplyTime(order.getdApplyLocalReturnTime());
			info.setSupportLocalRefund(order.isbCanLocalReturn());
			info.setReceiptConfirmedTime(order.getdConfirmedTime());
			return info;
		}

		// / <summary>
		// / 获取自动确认收货时间
		// / </summary>
		public static String GetAutoReceiveTime(C2COrderInfo order) {
			if (order == null)
				try {
					throw new Exception();
				} catch (Exception e) {
					e.printStackTrace();
				}
			return !order.isbPause() && order.getdFrozenTime() != null ? order.getdFrozenTime() : null;
		}

		/**
		 * 获取实付金额
		 * 
		 * @return
		 */
		public static BigDecimal GetAmountOfRealPay(C2COrderInfo order) {
			if (order != null) {
				BigDecimal pay = GetPrePaidAmount(order);
				BigDecimal postpay = GetPostPaidAmount(order);
				BigDecimal refund = GetRefundedAmount(order);
				return pay.add(postpay).subtract(refund);
			} else {
				return new BigDecimal(0);
			}
		}

		/**
		 * 获取退款金额
		 * 
		 * @param order
		 * @return
		 */
		public static BigDecimal GetRefundedAmount(C2COrderInfo order) {
			if (order != null) {
				BigDecimal amount = order.getfRefundedAmountOfCash().add(order.getfRefundedAmountOfGift())
								.add(order.getfRefundedAmountOfCoupon());
				if (amount.compareTo(new BigDecimal(0)) < 0) {
					try {
						throw new Exception("订单资金异常:" + order.getiOrderId());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return amount;
			}

			return new BigDecimal(0);
		}

		/**
		 * 获取补款金额
		 * 
		 * @return
		 * @throws Exception
		 */
		public static BigDecimal GetPostPaidAmount(C2COrderInfo order) {
			if (order != null) {
				BigDecimal amount = order.getfPostPaidAmountOfCash().add(order.getfPostPaidAmountOfGift())
								.add(order.getfPostPadiAmountOfCoupon());
				if (amount.compareTo(new BigDecimal(0)) < 0) {
					try {
						throw new Exception("订单资金异常:" + order.getiOrderId());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return amount;
			}
			return new BigDecimal(0);
		}

		// / <summary>
		// / 获取首付款金额
		// / </summary>
		public static BigDecimal GetPrePaidAmount(C2COrderInfo order) {
			if (order != null) {
				BigDecimal amount = order
								.getfPaidAmountOfCash()
								.add(order.getfPaidAmountOfGift())
								.add(order.getfPaidAmountOfFreeCard())
								.add((order.getfPaidAmountOfYmtCoupon().compareTo(new BigDecimal(0)) > 0 || order
												.getfPaidAmountOfSellerCoupon().compareTo(new BigDecimal(0)) > 0) ? order
												.getfPaidAmountOfYmtCoupon().add(order.getfPaidAmountOfSellerCoupon())
												: order.getfPaidAmountOfCoupon());

				if (amount.compareTo(new BigDecimal(0)) < 0) {
					try {
						throw new Exception("订单资金异常:" + order.getiOrderId());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return amount;
			} else {
				return new BigDecimal(0);
			}
		}

		// / <summary>
		// / 获取订单所属平台信息
		// / </summary>
		// / <param name="orderType">订单类型</param>
		// / <param name="orderSource">订单来源</param>
		public static int GetPlatformEnumInfo(int orderType, String orderSource) {
			String source = orderSource == null ? StringUtils.EMPTY : orderSource.toUpperCase();

			switch (source) {
			case "APP":
				return PlatformEnum.Ymt_APP.getValue();
			case "PC":
				return PlatformEnum.Ymt_PC.getValue();
			case "WAP":
				return PlatformEnum.Ymt_WAP.getValue();
			case "C2CAPP":
				return PlatformEnum.Ymt_C2CAPP.getValue();
			case "C2CWAP":
				return PlatformEnum.Ymt_C2CWAP.getValue();
			case "C2CWechat":
				return PlatformEnum.Ymt_C2CWechat.getValue();
			case "Wechat":
				return PlatformEnum.Ymt_Wechat.getValue();
			default:
				return PlatformEnum.Ymt_Other.getValue();
			}
		}
	}

	/**
	 * 订单信息转换器. 原ConvertOrderListToOrderInfoList
	 * 
	 * @param orderResult
	 * @param forSeller
	 * @return
	 */
	public static List<com.ymatou.query.seller.trading.api.parameter.OrderInfo> AsOrderInfos(OrderEntities orderResult,
					boolean forSeller) {
		if (orderResult == null || orderResult.getOrders() == null || orderResult.getCreditDetails() == null
						|| orderResult.getOrderNotes() == null || orderResult.getOrderStates() == null
						|| orderResult.getPostPays() == null || orderResult.getOrderInfos() == null
						|| orderResult.getOrderSummaries() == null || orderResult.getOrderFrozens() == null
						|| orderResult.getOrderToBills() == null) {
			return null;
		}

		return ConvetToOrderInfos(orderResult, forSeller);
	}

	private static List<com.ymatou.query.seller.trading.api.parameter.OrderInfo> ConvetToOrderInfos(
					OrderEntities orderResult, boolean forSeller) {
		Map<String, Ymt_Bill> billsMap = orderResult.getBills().stream()
						.collect(Collectors.toMap(Ymt_Bill::getsBillId, x -> x));
		List<com.ymatou.query.seller.trading.api.parameter.OrderInfo> infos = new ArrayList<com.ymatou.query.seller.trading.api.parameter.OrderInfo>();
		for (Ymt_Order order : orderResult.getOrders()) {
			int oid = order.getiOrderId();
			List<Ymt_Order_Frozen> tempOrderFrozen = orderResult.getOrderFrozens().stream()
							.filter(x -> x.getiOrderId() == oid).collect(Collectors.toList());
			List<Ymt_OrderState> tempOrderState = orderResult.getOrderStates().stream()
							.filter(x -> x.getiOrderId() == oid).collect(Collectors.toList());
			List<Ymt_O_OrderNote> tempOrderNote = orderResult.getOrderNotes().stream()
							.filter(x -> x.getiOrderId() == oid).collect(Collectors.toList());
			List<Ymt_CreditDetail> tempCreditDetailInfo = orderResult.getCreditDetails().stream()
							.filter(x -> x.getsTargetId().equals(String.valueOf(oid))).collect(Collectors.toList());
			List<Ymt_TradingItem> tradingItem = orderResult.getTradingItems().stream()
							.filter(x -> x.getiOrderId() == oid).collect(Collectors.toList());
			List<Ymt_OrderExt> orderExt = orderResult.getOrderExts().stream().filter(x -> x.getiOrderId() == oid)
							.collect(Collectors.toList());

			List<Ymt_OrderInfo> tempOrderInfo = orderResult.getOrderInfos().stream()
							.filter(x -> x.getiOrderId() == oid).collect(Collectors.toList());
			List<Ymt_OrderInfo> temp = new ArrayList<Ymt_OrderInfo>();
			tempOrderInfo = tempOrderInfo == null ? temp : tempOrderInfo;
			List<Ymt_OrderSummary> orderSummaryInfo = orderResult.getOrderSummaries().stream()
							.filter(x -> x.getiOrderId() == oid).collect(Collectors.toList());
			// List<Ymt_OrderToBill> orderToBillInfo = orderResult
			// .getOrderToBills().stream()
			// .filter(x -> x.getiOrderId() == oid)
			// .collect(Collectors.toList());
			List<Ymt_OrderPostPay> postPays = orderResult.getPostPays().stream().filter(x -> x.getiOrderId() == oid)
							.collect(Collectors.toList());

			int autoReceivedDelay = Ymt_OrderExtension.GetAutoReceiveDelay(order, tempOrderInfo);
			// int tradingId = DataUtil.isNullOrEmpty(tradingItem) ? 0
			// : tradingItem.get(0).getiTradingId();
			int tradingId = DataUtil.isNullOrEmpty(tradingItem) ? 0 : tradingItem.stream()
							.max((x, y) -> x.getiTradingId() - y.getiTradingId()).get().getiTradingId();

			com.ymatou.query.seller.trading.api.parameter.OrderInfo info = new com.ymatou.query.seller.trading.api.parameter.OrderInfo();

			Ymt_O_OrderNote orderNote = null;
			if (DataUtil.isNullOrEmpty(tempOrderNote) == false) {
				orderNote = tempOrderNote.get(0);
			}
			Ymt_Order_Frozen orderFrozen = null;
			if (DataUtil.isNullOrEmpty(tempOrderFrozen) == false) {
				orderFrozen = tempOrderFrozen.get(0);
			}
			Ymt_OrderExt ext = null;
			if (DataUtil.isNullOrEmpty(orderExt) == false) {
				ext = orderExt.get(0);
			}
			Ymt_OrderState orderState = null;
			if (DataUtil.isNullOrEmpty(tempOrderState) == false) {
				orderState = tempOrderState.get(0);
			}
			Ymt_CreditDetail creditDetail = null;
			if (DataUtil.isNullOrEmpty(tempCreditDetailInfo) == false) {
				creditDetail = tempCreditDetailInfo.get(0);
			}
			// 订单基本信息
			SetBasicInfo(forSeller, info, order, tradingId, orderNote, orderFrozen, tempOrderInfo, ext,
							orderSummaryInfo);
			// 订单金额相关
			SetPriceInfo(info, order, orderState, postPays);
			// 订单收货人相关信息
			SetContactInfo(info, order);
			// 订单延迟收货信息
			SetDelayReceiveInfo(info, order, orderFrozen, autoReceivedDelay);
			// 订单优惠券信息
			SetCouponInfo(info, order);
			// 订单相关日期
			SetTimeInfo(info, order, orderFrozen, autoReceivedDelay);
			// 订单评价相关信息
			SetCreditInfo(creditDetail, info);
			infos.add(info);
		}
		return infos;
	}

	/**
	 * 订单金额相关
	 * 
	 * @param info
	 * @param order
	 * @param tempOrderState
	 * @param postPayList
	 */
	private static void SetPriceInfo(com.ymatou.query.seller.trading.api.parameter.OrderInfo info, Ymt_Order order,
					Ymt_OrderState tempOrderState, List<Ymt_OrderPostPay> postPayList) {
		info.setOrderPrice(order.getfOrderPrice());
		info.setPromotionReducedAmount(order.getfSellerPromotionAmount());
		info.setOrderDiscount(order.getfOrderDiscount());
		info.setFreight(order.getfFreight());
		info.setDiscount(order.getfDiscount());
		info.setPostPaidAmountOfGift(tempOrderState == null ? new Ymt_OrderState().getfPostPaidAmountOfGift()
						: tempOrderState.getfPostPaidAmountOfGift());
		info.setPostPaidAmountOfCoupon(tempOrderState == null ? new Ymt_OrderState().getfPostPadiAmountOfCoupon()
						: tempOrderState.getfPostPadiAmountOfCoupon());
		info.setRefund(Ymt_OrderExtension.GetRefundedAmount(order, tempOrderState));
		info.setNeedPostPay(Ymt_OrderExtension.GetNeedPostPayAmount(order, postPayList));
		// info.setRealPay(Ymt_OrderExtension.GetAmountOfRealPay(order,
		// tempOrderState));
		info.setRealPay(Ymt_OrderExtension.GetAmountOfRealPay(order, tempOrderState).subtract(info.getRefund()));
		info.setRealPaidAmountOfGift(Ymt_OrderExtension.GetReceiveAmountOfGift(tempOrderState));
		info.setNeedPrePayAmountOfCash(Ymt_OrderExtension.GetNeedPrePayAmountOfCash(order));
		info.setRealPostPay(Ymt_OrderExtension.GetPostPaidAmount(tempOrderState));
		info.setFirstPay(Ymt_OrderExtension.GetPrePaidAmount(order,tempOrderState));
		info.setTotalPrice(order.getfTotalPrice());
		info.setOldFreight(order.getfOldFreight());
		info.setOldDiscount(order.getfOldDiscount());
		info.setThirdPartyRefundStatus(order.getiThirdPartyRefundStatus());
		info.setRealPaidAmountOfCash(Ymt_OrderExtension.GetReceiveAmountOfCash(tempOrderState));
		info.setPaidAmountOfFreeCard(tempOrderState.getfPaidAmountOfFreeCard());
		info.setPaidAmountOfCoupon(tempOrderState.getfPaidAmountOfCoupon());
		info.setPaidAmountOfYmtCoupon(DataUtil.BigDecimall.GetValueOrDefault(tempOrderState.getfPaidAmountOfYmtCoupon()));
		info.setDiscountOfThirdParty(DataUtil.BigDecimall.GetValueOrDefault(tempOrderState.getfDiscountOfThirdParty()));
		info.setTotalRefundThirdPartyDiscount(DataUtil.BigDecimall.GetValueOrDefault(tempOrderState
						.getfRefundedDiscountOfThirdParty()));

		// if (order.isbShangouOrder()) {
		// if (order.isbPaidInFull()) {
		// info.setTotalPriceChange(DataUtil.BigDecimall.GetValueOrDefault(info.getFirstPay())
		// .add(DataUtil.BigDecimall.GetValueOrDefault(info.getRealPostPay()))
		// .subtract(DataUtil.BigDecimall.GetValueOrDefault(info.getTotalPrice())));
		// } else {
		// if (DataUtil.isNullOrEmpty(postPayList) == false) {
		// List<Ymt_OrderPostPay> t = postPayList.stream().filter(x ->
		// x.getiAction() == 0)
		// .collect(Collectors.toList());
		// if (DataUtil.isNullOrEmpty(t) == false) {
		// Ymt_OrderPostPay p = t.get(0);
		// info.setTotalPriceChange(DataUtil.BigDecimall.GetValueOrDefault(info.getFirstPay())
		// .add(DataUtil.BigDecimall.GetValueOrDefault(p.getfAmount()))
		// .subtract(DataUtil.BigDecimall.GetValueOrDefault(info.getTotalPrice())));
		// }
		// }
		// }
		// } else {
		// info.setTotalPriceChange(DataUtil.BigDecimall.GetValueOrDefault(order.getfOrderDiscount()));
		// }

		info.setTotalPriceChange(DataUtil.BigDecimall.GetValueOrDefault(order.getfOrderDiscount()).add(
						DataUtil.BigDecimall.GetValueOrDefault(order.getfDiscount())));

		if (DataUtil.Integerr.GetValueOrDefault(order.getiSalesRefundStatus()) == 10) {
			info.setTotalSalesRefundAmount(order.getTotalSalesRefundAmount());
		}
	}

	/**
	 * 订单基本信息
	 * 
	 * @param forSeller
	 * @param info
	 * @param order
	 * @param tradingId
	 * @param tempOrderNote
	 * @param tempOrderFrozen
	 * @param productInfos
	 * @param orderExt
	 * @param orderSummaryInfo
	 * @param orderToBillInfo
	 * @param billsMap
	 */
	private static void SetBasicInfo(boolean forSeller, com.ymatou.query.seller.trading.api.parameter.OrderInfo info,
					Ymt_Order order, int tradingId, Ymt_O_OrderNote tempOrderNote, Ymt_Order_Frozen tempOrderFrozen,
					List<Ymt_OrderInfo> productInfos, Ymt_OrderExt orderExt, List<Ymt_OrderSummary> orderSummaryInfo) {
		info.setOrderId(order.getiOrderId());
		info.setUserId(order.getiUserId());
		info.setBuyerId(order.getiBuyerId());
		info.setAddTime(order.getdAddTime());
		info.setAcceptTime(order.getdAcceptTime());
		info.setTradingId(tradingId);
		info.setTradingStatus(order.getiTradingStatus());// Common.GetOrderStatusForSeller(order.iTradingStatus,
															// order.iRiskVerifiedStatus,
															// forSeller);
		info.setRiskVerifiedStatus(order.getiRiskVerifiedStatus());
		info.setOperate(order.getiOperate());
		info.setOperateExpireTime(order.getdOperateExpireTime());
		info.setReplyTopicWhenOrderPaid(order.getiReplyTopicWhenOrderPaid());
		info.setPaidInFull(order.isbPaidInFull());
		info.setUseGiftAmount(order.getfUseGiftAmount());
		info.setTopicId(order.getiTopicId());
		info.setTitle(order.getsTitle());
		info.setUnfreezeStatus(order.getiUnfreezeStatus());
		info.setShangouOrder(order.isbShangouOrder());
		info.setBuyerLoginId(order.getsBuyerLoginId());
		info.setBuyerLoginEmail(order.getsBuyerLoginEmail());
		info.setSellerLoginId(order.getsSellerLoginId());
		info.setSellerLoginEmail(order.getsSellerLoginEmail());
		info.setIsMerchant(order.getiIsMerchant());
		info.setBuyerNickName(order.getsBuyerNickName());
		info.setDispathTime(order.getdDispathTime());
		info.setDistributor(order.getiDistributor());
		info.setThirdOrderId(order.getsThirdOrderId());
		info.setIsShippedByXlobo(order.isbShippedByXlobo());
		info.setType(order.getiType());
		info.setUseFreeCardAmount(order.getfUseFreeCardAmount());
		info.setSellerNote(tempOrderNote != null ? tempOrderNote.getsContent() : DataUtil.Stringg.Empty);
		info.setFrozen(tempOrderFrozen != null && tempOrderFrozen.isbFrozen());

		List<OrderItemInfo> OrderItemInfos = new ArrayList<OrderItemInfo>();
		productInfos.stream().forEach(x -> OrderItemInfos.add(Ymt_OrderInfoExtension.ConvertToOrderItemInfo(x)));
		info.setOrderItemList(OrderItemInfos);
		// info.setOrderItemList(productInfos.stream()
		// .map(x -> Ymt_OrderInfoExtension.ConvertToOrderItemInfo(x))
		// .collect(Collectors.toList()));

		info.setLogisticsType(productInfos.size() > 0 ? productInfos.get(0).getiCatalogStatus()
						: LogisticsTypeEnum.Unknown.getValue());
		info.setStockStatus(productInfos.size() > 0 ? productInfos.get(0).getiCatalogType() : StockStatusEnum.Spot
						.getValue());
		info.setBillCodeList(orderSummaryInfo.stream().map(x -> x.getsSummary()).collect(Collectors.toList()));
		info.setOrderSummaryList(orderSummaryInfo.stream().map(x -> Ymt_OrderSummaryExtension.ConvertToOrderSummary(x))
						.collect(Collectors.toList()));
		List<BillInfo> billInfoList = new ArrayList<BillInfo>();
		info.setBillInfoList(billInfoList);

		info.setSupportLocalRefund(order.isbCanLocalReturn());

		info.setLocalRefundApplyTime(order.getdApplyLocalReturnTime());
		info.setSalesRefundStatus(order.getiSalesRefundStatus());

		info.setCancelReason(order.getsReason());
		info.setPackageDelivery_DomesticDelivered(Common.GetPackageDeliveryDomesticDeliveredStatus(DataUtil.Integerr
						.GetValueOrDefault(order.getiTradingStatus()),
						DataUtil.isNullOrEmpty(productInfos) ? new Ymt_OrderInfo().getiCatalogStatus() : productInfos
										.get(0).getiCatalogStatus(), order.getbDomesticDelivered()));
		info.setMainOrderId(order.getiMainOrderId());
		info.setYmtCouponAmount(order.getfYmtCouponAmount());
		info.setYmtCouponCode(order.getsYmtCouponCode());
		info.setSellerCouponAmount(DataUtil.BigDecimall.GetValueOrDefault(order.getfSellerCouponAmount()));
		info.setSellerCouponCode(order.getsSellerCouponCode());
		info.setPayableAmount(order.getfPayableAmount());

		info.setRealSettlementAmountOfCoupon(order.getRealSettlementAmountOfCoupon());
		// info.setTotalRefundThirdPartyDiscount(order
		// .getTotalRefundThirdPartyDiscount());

		info.setPreSaleOrder(DataUtil.Booleann.GetValueOrDefault(order.getbPreSale()));
		
		info.setRemarkLevel(tempOrderNote != null ? tempOrderNote.getiRemarkLevel() : null);
		List<Integer> t = null;
		if (DataUtil.Stringg.isNullOrEmpty(order.getBusynessTypes()) == false) {
			t = new ArrayList<Integer>();
			String[] ss = order.getBusynessTypes().split(",");
			for (String s : ss) {
				if (!s.trim().equals("")) {
					t.add(Integer.valueOf(s));
				}
			}
		}
		info.setBusynessTypeList(t);

		if (orderExt != null) {
			info.setPlatformEnum(BuyerAppOrderInfoBuilder.GetPlatformEnumInfo(orderExt.getiOrderType(),
							orderExt.getsOrderSource()));
			info.setNeedUploadIdCard(orderExt.isbIsNeedUploadIdCard());
			info.setHaveUploadedIdCard(orderExt.isbHaveUploadedIdCard());
			info.setIsNewSellerOrder(orderExt.getbNewSellerOrder());
			info.setIsNewCustomerOrder(orderExt.getbNewCustomerOrder());
			info.setIsFirstOrder(orderExt.isbIsFirstOrder());
		}
	}

	/**
	 * 订单收货人相关信息
	 * 
	 * @param info
	 * @param order
	 */
	private static void SetContactInfo(com.ymatou.query.seller.trading.api.parameter.OrderInfo info, Ymt_Order order) {
		info.setAddress(order.getsAddress());
		info.setPostCode(order.getsPostCode());
		info.setReceivePerson(order.getsReceivePerson());
		info.setPhone(order.getsPhone());
		info.setTelephone(order.getsTelephone());
		info.setQQ(order.getsQQ());
		info.setEmail(order.getsEmail());
		info.setLeaveWord(order.getsLeaveWord());
	}

	/**
	 * 订单延迟收货信息
	 * 
	 * @param info
	 * @param order
	 * @param tempOrderFrozen
	 * @param autoReceivedDelay
	 */
	private static void SetDelayReceiveInfo(com.ymatou.query.seller.trading.api.parameter.OrderInfo info,
					Ymt_Order order, Ymt_Order_Frozen tempOrderFrozen, int autoReceivedDelay) {
		info.setDelayReceiveFrozened(order.getdDispathTime() != null
						&& tempOrderFrozen != null
						&& tempOrderFrozen.getdFrozenTime() != null
						&& tempOrderFrozen.getiUserId() != null
						&& YMTDateUtil.parseYMDHMSDate(tempOrderFrozen.getdFrozenTime())
										.after(YMTDateUtil.parseYMDHMSDate(YMTDateUtil.getBeforeOrNextDay(
														order.getdDispathTime(), autoReceivedDelay, YMTDateUtil.YMDHMS))));
		info.setDelayReceiveFrozenTime(tempOrderFrozen != null ? tempOrderFrozen.getdFrozenTime() : null);
		info.setDelayReceiveUpdateTime(tempOrderFrozen != null ? tempOrderFrozen.getdUpdateTime() : null);
		info.setDelayReceiveAddTime(tempOrderFrozen != null ? tempOrderFrozen.getdAddTime() : defaultDateTime);
		info.setDelayReceiveUserId(tempOrderFrozen != null && tempOrderFrozen.getiUserId() != null ? tempOrderFrozen
						.getiUserId() : order.getiBuyerId());
	}

	/**
	 * 订单优惠券信息
	 * 
	 * @param info
	 * @param order
	 */
	private static void SetCouponInfo(com.ymatou.query.seller.trading.api.parameter.OrderInfo info, Ymt_Order order) {
		if (DataUtil.BigDecimall.GetValueOrDefault(order.getfYmtCouponAmount()).compareTo(new BigDecimal(0)) > 0
						|| DataUtil.BigDecimall.GetValueOrDefault(order.getfSellerCouponAmount()).compareTo(
										new BigDecimal(0)) > 0) {
			info.setCouponCode(order.getsYmtCouponCode());
			info.setCouponValue(order.getfYmtCouponAmount());

			info.setSellerCouponCode(order.getsSellerCouponCode());
			info.setSellerCouponAmount(order.getfSellerCouponAmount());
		} else {
			if (order.getiCouponChannel() == 2) {
				info.setSellerCouponCode(order.getsCouponCode());
				info.setSellerCouponAmount(DataUtil.BigDecimall.GetValueOrDefault(order.getCouponValue()));
			} else {
				if (DataUtil.BigDecimall.GetValueOrDefault(info.getCouponValue()).compareTo(new BigDecimal(0)) > 0) {
					info.setCouponCode(order.getsCouponCode());
					info.setCouponValue(DataUtil.BigDecimall.GetValueOrDefault(order.getCouponValue()));
				}
			}
		}

		info.setCouponType(order.getiCouponType());
	}

	/**
	 * 订单相关日期
	 * 
	 * @param info
	 * @param order
	 * @param tempOrderFrozen
	 * @param autoReceivedDelay
	 */
	private static void SetTimeInfo(com.ymatou.query.seller.trading.api.parameter.OrderInfo info, Ymt_Order order,
					Ymt_Order_Frozen tempOrderFrozen, int autoReceivedDelay) {
		info.setPaidTime(order.getdPaidTime());
		info.setApplyPostPayTime(order.getdApplyPostPayTime());
		info.setPostPaidTime(order.getdPostPaidTime());
		info.setConfirmedTime(order.getdConfirmedTime());
		info.setChangeAddressTime(order.getdChangeAddressTime());
		info.setDiscountTime(order.getdDiscountTime());
		info.setCancelTime(order.getdCancelTime());
		info.setDispatchTime(order.getdDispathTime());
		info.setAutoCancelOrderHours(order.getfAutoCancelOrderHours());

		String t = Ymt_OrderExtension.GetAutoReceiveTime(tempOrderFrozen, autoReceivedDelay);

		info.setIsAutoReceiveEnabled(t != null);
		info.setAutoReceiveTime(t != null ? t : "9999-12-31 23:59:59");
	}

	/**
	 * 订单评价相关信息
	 * 
	 * @param creditInfo
	 * @param orderInfo
	 */
	private static void SetCreditInfo(Ymt_CreditDetail creditInfo,
					com.ymatou.query.seller.trading.api.parameter.OrderInfo orderInfo) {
		if (creditInfo != null) {
			orderInfo.setCredited(true);
			orderInfo.setCreditId(creditInfo.getiCreditDetailId());
			orderInfo.setCreditUserId(creditInfo.getiUserId());
			orderInfo.setCreditServiceRange(creditInfo.getfPoint().intValue());
			orderInfo.setCreditUniformityRange(creditInfo.getfPoint2() == null ? 0 : creditInfo.getfPoint2().intValue());
			orderInfo.setCreditScoreRange(creditInfo.getiPoint3());
			orderInfo.setCreditDescript(creditInfo.getsDescription());
			orderInfo.setCreditAddTime(creditInfo.getdAddTime());
			orderInfo.setCreditUpdateTime(creditInfo.getdUpdateTime());
			orderInfo.setCreditSellerReply(creditInfo.getsSellerReply());
			orderInfo.setCreditSellerReplyUpdateTime(creditInfo.getdSellerReplyUpdateTime() == null ? YMTDateUtil
							.getSysTime() : creditInfo.getdSellerReplyUpdateTime());
		} else {
			orderInfo.setCredited(false);
		}
	}
}
